package org.jdemo.tools.encoding;

import org.jdemo.util.IOUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Transformer
 *
 * @author longlin(longlin@cyou-inc.com)
 * @date 2014/12/28
 * @since V1.0
 */
public class Transformer {
    public static void main(String[] args) {
        transform("D:\\myspace\\space_android_study", "(.*)src(.*)\\.java", "UTF-8", "UTF-8");
    }

    public static void transform(String path, String filter, String sourceEncoding, String targetEncoding) {
        List<String> filePaths = recursiveReadFile("D:\\myspace\\space_android_study", "(.*)src(.*)\\.java");
        int total = filePaths.size();
        int current = 1;
        for (String filePath : filePaths) {
            String content = IOUtil.readFile(filePath, sourceEncoding);
            IOUtil.writeFile(content, filePath, targetEncoding, false);
            double percent = Math.round(current * 10000.0 / total) / 100.0;
            System.out.println("finished["  + percent + "%]:" + filePath);
            ++current;
        }
    }

    public static List<String> recursiveReadFile(String dirPath, String filter) {
        List<String> filePaths = new ArrayList<String>();

        File dir = new File(dirPath);
        File[] files = dir.listFiles();
        for (File file : files) {
            String filePath = file.getPath();
            if (file.isDirectory()) {
                filePaths.addAll(recursiveReadFile(filePath, filter));
            } else {
                if (filePath.matches(filter)) {
                    filePaths.add(filePath);
                }
            }
        }
        return filePaths;
    }
}
